package com.example.weather_news.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import com.android.volley.Response;
import com.example.weather_news.R;
import com.example.weather_news.db.CityInfo;
import com.example.weather_news.http.HttpRequest;
import com.example.weather_news.util.ShareUtils;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

public class FlashActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        boolean b= ShareUtils.getBoolean(FlashActivity.this,ShareUtils.FLASH,true);
        if (b){
            startActivity(new Intent(FlashActivity.this,MainActivity.class));
            finish();
            return;
        }
        setContentView(R.layout.activity_flash);

        if (Build.VERSION.SDK_INT >= 21) {
            View view = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            view.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }

        if (DataSupport.findAll(CityInfo.class).size()==0){
            queryCity();
        }

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                startActivity(new Intent(FlashActivity.this, MainActivity.class));
                finish();
            }
        }, 2000);
    }

    private void queryCity() {
        HttpRequest.requestCity(new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                try {
                    if (jsonObject.getInt("status") != 0) {
                        return;
                    }
                    JSONArray array = new JSONArray(jsonObject.getString("result"));
                    Log.e("array1", array.length() + "");
                    Gson gson = new Gson();
                    CityInfo info;
                    for (int i = 0; i < array.length(); i++) {
                        info = gson.fromJson(array.getJSONObject(i).toString(), CityInfo
                                .class);
                        info.save();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, null);

    }
}
